package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.GetThreadLocal;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/10/31 10:15
 * <p>
 * 验证是否登录拦截器
 */
@Slf4j
@WebFilter("/*")
//@Order(2)
public class loginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取请求资源
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        // 2. 判断请求资源是否是需要放行的资源
        boolean result = isTrue(uri);
        // 3. true说明匹配上了就放行
        if (result) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 4. false没有匹配说明不需要放行，判断是否登录
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        // 5. 如果session中有对象，说明已经登录成功
        if (employee != null) {
            filterChain.doFilter(servletRequest, servletResponse);
            // 6. 如果没有登录，就给前端响应未登录
            return;
        }

        // 判断c端用户是否登录
        Long userId = (Long) session.getAttribute("user");
        if (userId != null) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }

    /**
     * 用来判断，请求资源是否和需要放行的资源相匹配
     *
     * @param uri
     * @return
     */
    private boolean isTrue(String uri) {
        String[] uris = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/common/upload",
                "/common/download",
                "/user/sendMsg",
                "/user/login"
        };
        // 路径匹配器
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String s : uris) {
            if (antPathMatcher.match(s, uri)) {
                return true;
            }
        }
        return false;
    }
}

